require 'rubygems'
require 'open-uri'

class StoreController < ApplicationController
  before_filter :buddy?,:only=>[:handbook]
  before_filter :login_required,:only => [:mine,:my_cart,:my_favorite,:buy_history]
  before_filter :find_user,:only=>[:mine,:my_cart,:my_favorite,:buy_history]
  before_filter :him_or_her,:only=>[:for_him,:for_her]
  before_filter :build_order_conditions,:only=>[:mine,:print]
  before_filter :empty_cart_or_not,:mark_agent_id,:only=>[:for_him,:for_her,:index]
  #  protect_from_forgery :except => [:add_province,:add_city,:add_region]
  def index
    @designs = Design.find(:all,:limit=>12,:conditions=>{:active=>1},:order=>'id desc')
    @recommend_designs = Design.recommend_list
    @male_materials = Material.find_by_sex(Style::MALE,12)
    @female_materials = Material.find_by_sex(Style::FEMALE,12)
  end

  def add_to_cart
    begin
      Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid product #{params[:id]}")
      redirect_to_index("添加商品到购物车出错")
    else
      quantity = params[:quantity] ? (params[:quantity].to_i):1
      @current_item = @cart.add_product(params[:id],params[:tee_size],quantity)
      redirect_to :action=>:my_cart
    end
  end

  def my_cart

  end

  def remove_from_cart
    @cart.items.each do |i|
      @cart.items.delete(i)   if i.product_id == params[:id] && i.tee_size == params[:size]
    end
    render :template=>'/store/_cart',:layout=>false
  end

  def decrease_from_cart
    @cart.items.each do |i|
      i.decrement_quantity   if i.product_id == params[:id] && i.tee_size == params[:size]
      @cart.items.delete(i) if i.quantity == 0
    end
    render :template=>'/store/_cart',:layout=>false
  end

  def increase_from_cart
    @cart.items.each do |i|
      i.increment_quantity   if i.product_id == params[:id] && i.tee_size == params[:size]
    end
    render :template=>'/store/_cart',:layout=>false
  end

  def empty_cart
    session[:cart] = nil
    render :text=>'ok'
  end

  def for_him
    @params_string = params[:product].to_a.map{|c| "e_#{c[0]}=#{c[1]}"}.join("&") if params[:product]
  end

  def for_her
    @params_string = params[:product].to_a.map{|c| "e_#{c[0]}=#{c[1]}"}.join("&") if params[:product]
  end

  def mine
    unless merchandiser?
      @orders = @user.orders.paginate :page => params[:page],:per_page =>20,:conditions=>@coditions,:order=>'id desc'
      @products = @user.products.paginate :page => params[:page],:per_page => 5,:order=>"id desc"
    else
      @orders = Order.paginate :all,:page => params[:page],:per_page =>20,:conditions=>@coditions,:order=>'id desc'
    end

    if agent?
      @domain = DOMAIN
      @photos = Photo.find(:all)
    end
  end

  def my_favorite

  end

  def buy_history

  end

  def print
    if params[:id]
      @orders = Order.find :all,:conditions=>["id = ?",params[:id]]
    else
      @orders = Order.find :all,:conditions=>@coditions,:order=>'id desc'
    end
    render :layout=>false
  end

  #  def get_fashion
  #    iconv=Iconv.new("UTF-8//IGNORE","GB2312//IGNORE")
  #    return_string =""
  #    Rssfeed.find(:all).each do |r|
  #      rss = SimpleRSS.parse open(r.url)
  #      return_string += "<span class='rss_title'>#{r.name}</span><br />"
  #      return_string += rss.entries.first(r.quantity).map{|c|"<a class='fashion_link' href='#{c.link}' target='_blank'>#{iconv.iconv(c.title)}</a>"}.join("<br/>")
  #      return_string += "<br />"
  #    end
  #
  #    return_string.gsub!("]]>","")
  #    render :text=>return_string
  #  end

  def tips
    
  end

  #  def price_list
  #    @materials = Material.find(:all)
  #    @designs = Design.find(:all)
  #  end

  def calculate_fee
    if params[:logistic_id] && params[:address_id]
      logistic = Logistic.find(params[:logistic_id])
      if @cart.total_items >=logistic.free_quantity && logistic.free_quantity >0
        render :text=>"#{@cart.total_items}件免运费"
      else
        province_id =  Address.find(params[:address_id]).province_id
        logistic_fee = LogisticFee.find_by_province_id_and_logistic_id(province_id,logistic.id)

        if logistic_fee
          render :text=>"<span class='yen'>" + logistic_fee.fee.to_s + "</span>"
        else
          render :text=>"<span class='yen'>" + logistic.default_fee.to_s + "</span>"
        end
      end
    else
      render :text=>""
    end
  end

  def help_center
    @article = Article.help_center
    render :template=>'/articles/show'
  end

  def about
    @article = Article.about
    render :template=>'/articles/show'
  end

  def handbook
  end

  def order_success_tips
    @order = Order.find(params[:id])
  end


  def materials
    sql = "select m.* from styles s,materials m
      where s.id = m.style_id and m.active = 1 and s.active"

    if params[:sex]
      sql += " and s.sex =#{params[:sex]}"
    end

    @materials = Material.paginate_by_sql sql,
      :page => params[:page],:per_page =>18,:order=>"m.style_id desc"
  end

  def success
    flash[:notice] = "支付成功！多谢惠顾，请留意我们的发货邮件。"
    render :action=>:tips
  end

  #  def create_new_size
  #    Material.create_new_size("thumb","90X90")
  #    render :text=>"ok"
  #  end


  #  def add_province
  #    data = JSON.parse(params[:data])
  #    count = 0
  #    data["province"].each do |p|
  #      count +=1
  #      province = Province.create(:name=>p["name"])
  #      p["city"].sort!{|a,b|a["post_code"]<=>b["post_code"]}
  #      p["city"].each do |c|
  #        city = province.cities.create(:name=>c["name"],:post_code=>c["post_code"],:long_distance_code=>c["long_distance_code"])
  #        c["region"].sort!{|a,b|a["post_code"]<=>b["post_code"]}
  #        c["region"].each do |r|
  #          city.regions.create(:name=>r["name"],:post_code=>r["post_code"])
  #        end
  #      end
  #    end
  #    render :text=>count.to_s
  #  end

  #  def get_province
  #    json_data =  Province.find(:all,:include=>:cities).map{|p|
  #      {"id"=>p.id,"name"=>p.name,
  #        "cities"=>p.cities.map{|c|{"id"=>c.id,"name"=>c.name,
  #            "post_code"=>c.post_code,
  #            "long_distance_code"=>c.long_distance_code,
  #            "region"=>c.regions.map{|r|{"id"=>r.id,"name"=>r.name,"post_code"=>r.post_code}}
  #          }
  #        }
  #
  #      }
  #    }
  #    render :text=>json_data.to_json
  #  end

  private

  def him_or_her
    session[:him_or_her] = action_name
  end

  def empty_cart_or_not
    session[:cart] = nil if params[:empty_cart]
  end

  def build_order_conditions
    if params[:status] && !params[:start_date].blank? && !params[:end_date].blank?
      @coditions = ["status = ? and created_at >= ? and created_at <= ?",params[:status],params[:start_date],params[:end_date]]
    elsif params[:status]
      @coditions = ["status = ?",params[:status]]
    else
      @coditions = ""
    end
  end
end
